package com.xiaotao.captcha.controller;

import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.spring.annotation.Captcha;
import cloud.tianai.captcha.spring.application.ImageCaptchaApplication;
import cloud.tianai.captcha.spring.plugins.secondary.SecondaryVerificationApplication;
import cloud.tianai.captcha.spring.request.CaptchaRequest;
import cloud.tianai.captcha.spring.vo.CaptchaResponse;
import cloud.tianai.captcha.spring.vo.ImageCaptchaVO;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import com.xiaotao.commons.common.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author xiaotao
 * @create 2023/3/1 10:02
 */
@Slf4j
@RestController
@RequestMapping("api")
@AllArgsConstructor
public class CaptchaController {
    private final ImageCaptchaApplication imageCaptchaApplication;
    // 只需要在需要验证的controller层加入 @Captcha 注解，
    // 并且接受的参数指定成CaptchaRequest即可自动进行校验
    // 自己真实的参数可以写到 CaptchaRequest对象的泛型中
    // 如果校验失败，会抛出CaptchaValidException异常
    // 对校验失败的处理，可以使用sping的全局异常拦截CaptchaValidException异常进行处理

//    @Captcha("SLIDER")
    @PostMapping("captcha")
    public R<CaptchaResponse<ImageCaptchaVO>> login(@RequestParam(value = "type", required = false) String type) {
        if (StringUtils.isBlank(type)){
            type = CaptchaTypeConstant.SLIDER;
        }
        return R.success(imageCaptchaApplication.generateCaptcha(type));
    }



    @PostMapping("/check")
    @ResponseBody
    public Object checkCaptcha(@RequestParam("id") String id,
                                @RequestBody ImageCaptchaTrack imageCaptchaTrack,
                                HttpServletRequest request) {
        return imageCaptchaApplication.matching(id, imageCaptchaTrack);
    }

  /**
   * 二次验证，一般用于机器内部调用，这里为了方便测试
   *
   * @param id id
   * @return boolean
   */
  @GetMapping("/check2")
  @ResponseBody
  public boolean check2Captcha(@RequestParam("id") String id) {
    // 如果开启了二次验证
    if (imageCaptchaApplication instanceof SecondaryVerificationApplication) {
      return ((SecondaryVerificationApplication) imageCaptchaApplication).secondaryVerification(id);
    }
    return false;
  }
}
